﻿using System;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace CameraDemo
{
    /// <summary>
    ///     An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private const String photoKey = "capturedPhoto";
        private IPropertySet appSettings;

        public MainPage()
        {
            InitializeComponent();
            appSettings = ApplicationData.Current.LocalSettings.Values;
            ResetButton.Visibility = Visibility.Collapsed;
            Loaded += MainPage_Loaded;
        }

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Reload previously taken photo
            if (appSettings.ContainsKey(photoKey))
            {
                object filePath;
                if (appSettings.TryGetValue(photoKey, out filePath) && filePath.ToString() != "")
                {
                    CaptureButton.IsEnabled = false;
                    await ReloadPhoto(filePath.ToString());
                    CaptureButton.IsEnabled = true;
                }
            }
        }

        private async void CapturePhoto_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new CameraCaptureUI();
                var aspectRatio = new Size(16, 9);
                dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;

                StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
                if (file != null)
                {
                    var bitmapImage = new BitmapImage();
                    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
                    {
                        bitmapImage.SetSource(fileStream);
                    }
                    CapturedPhoto.Source = bitmapImage;

                    // Store the file path in Application Data
                    appSettings[photoKey] = file.Path;
                    ResetButton.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            ResetButton.Visibility = Visibility.Collapsed;
            CapturedPhoto.Source = new BitmapImage(new Uri(this.BaseUri, "Assets/StoreLogo.png"));

            // Clear file path in Application Data
            appSettings.Remove(photoKey);
        }

        /// <summary>
        /// Loads the photo from file path
        /// </summary>
        /// <param name="filePath">The path to load the photo from</param>
        private async Task ReloadPhoto(String filePath)
        {
            try
            {
                StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
                BitmapImage bitmapImage = new BitmapImage();
                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
                {
                    bitmapImage.SetSource(fileStream);
                }
                CapturedPhoto.Source = bitmapImage;
                ResetButton.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                appSettings.Remove(photoKey);
            }
        }
    }
}